//
//  LSZDynamicDetailsEvaluationViewController.m
//  JKFuYinProject
//
//  Created by 九酷 on 2018/8/22.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LSZDynamicDetailsEvaluationViewController.h"

@interface LSZDynamicDetailsEvaluationViewController ()<UITableViewDelegate,UITableViewDataSource,UITextViewDelegate>
@property(nonatomic,strong) UITableView * tableViewCommentDetails;
@property(nonatomic,strong) UIView * lowView;
@property(nonatomic,strong) UITextView * textView;
@property(nonatomic,strong) UILabel * uilabel;

@property(nonatomic,assign) NSInteger page;
@property(nonatomic,assign) NSInteger indexNum;
@property(nonatomic,strong) NSMutableArray * arrayTwoData;
@end

@implementation LSZDynamicDetailsEvaluationViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.page = 1;
    [self GetAreplyListOfComments:self.page];
}
#pragma mark - 获取回复的列表
-(void)GetAreplyListOfComments :(NSInteger)page
{
    __weak typeof(self) weakSelf = self;
    [LSZRequestResolutionDic dynamicCommentDetails:@"" tid:self.dynamicCommentDetailsMg.tid comment_id:self.dynamicCommentDetailsMg.id_id selfUser:@"" page:[NSString stringWithFormat:@"%ld",(long)page] :^(BOOL isOk, NSString * string, LSZDynamicCommentDetailsManager * manager) {
        if (isOk ==YES) {
            if (page == 1) {
                [weakSelf.arrayTwoData  removeAllObjects];
                [weakSelf.arrayTwoData addObjectsFromArray:manager.arrayData];
                if (manager.arrayData.count == 0) {
                    weakSelf.tableViewCommentDetails.mj_footer.hidden = YES;
                }
            }else{
                if (manager.arrayData.count >0) {
                    [weakSelf.arrayTwoData addObjectsFromArray:manager.arrayData];
                }else{
                    weakSelf.page = weakSelf.page - 1;
                    [weakSelf.tableViewCommentDetails.mj_footer endRefreshingWithNoMoreData];
                }
            }
            [weakSelf.tableViewCommentDetails reloadData];
        }else{
            [weakSelf setStringWarning:string];
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"评论的详情";
    self.arrayTwoData = [[NSMutableArray alloc]init];
    [self setTableView];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        CGFloat intFont = [LSZSpecialPackaging initWithReturnsthesizeOf:14 :0.5];
         CGFloat addHeight = [LSZSpecialPackaging initWithReturnsthesizeOf:60 :4];
        CGFloat height = [LSZSpecialPackaging caculateHeightOfText:ScreenWidth-30 height:10000 font:intFont :self.dynamicCommentDetailsMg.content]+addHeight;
        return height;
    }else{
        LSZResourceEvaluationListMg * mg = nil;
        mg = self.arrayTwoData[indexPath.row];
        CGFloat intFont = [LSZSpecialPackaging initWithReturnsthesizeOf:14 :0.5];
        CGFloat addHeight = [LSZSpecialPackaging initWithReturnsthesizeOf:60 :4];
        CGFloat height = [LSZSpecialPackaging caculateHeightOfText:ScreenWidth-30 height:10000 font:intFont :mg.content]+addHeight;
        return height;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return [LSZSpecialPackaging initWithReturnsthesizeOf:40 :5];
    }else{
        return 0.001;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return self.arrayTwoData.count;
    }
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.arrayTwoData.count >0) {
        return 2;
    }else{
        return 1;
    }
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if(section == 0){
        LSZHeaderLabelCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"LSZHeaderLabelCell"];
        if(self.arrayTwoData.count == 0){
            cell.label.text = @"暂无回复";
        }else{
            cell.label.text = @"全部回复";
        }
        cell.viewLow.hidden = YES;
        return cell;
    }
    UITableViewHeaderFooterView * foot = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!foot) {
        foot = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"foot"];
    }
    return foot;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LSZAppraiseTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZAppraiseTableViewCell" forIndexPath:indexPath];
    __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0) {
        cell.contentView.backgroundColor =  [UIColor whiteColor];
        cell.labelName.text = [NSString stringWithFormat:@"%@",weakSelf.dynamicCommentDetailsMg.username];
        cell.labelZanNumber.text = [NSString stringWithFormat:@"%@",weakSelf.dynamicCommentDetailsMg.admire_num];
        cell.labelContent.text = [NSString stringWithFormat:@"%@",weakSelf.dynamicCommentDetailsMg.content];
        cell.labelTime.text = [NSString stringWithFormat:@"%@",weakSelf.dynamicCommentDetailsMg.add_time];
        [cell.imageViewHeader sd_setImageWithURL:[NSURL URLWithString: weakSelf.dynamicCommentDetailsMg.avatar] placeholderImage:[UIImage  imageNamed:@"placeholder"]];
        CGFloat intFont = [LSZSpecialPackaging initWithReturnsthesizeOf:14 :0.5];

        CGFloat height = [LSZSpecialPackaging caculateHeightOfText:ScreenWidth-30 height:10000 font:intFont :weakSelf.dynamicCommentDetailsMg.content];
        CGRect rect = cell.labelContent.frame;
        rect.size.height = height;
        cell.labelContent.frame = rect;
        [cell.imageViewHeader tapGesture:^(UIGestureRecognizer *ges) {
            //个人信息页
            LSZPersonalInformationPageVC * vc = [[LSZPersonalInformationPageVC alloc]init];
            vc.uid = weakSelf.dynamicCommentDetailsMg.uid;
            vc.imageViewHeader = weakSelf.dynamicCommentDetailsMg.avatar;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        UITapGestureRecognizer *tapNumber = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickZanBut)];
        [cell.labelZanNumber addGestureRecognizer:tapNumber];

        UITapGestureRecognizer *tapShou = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickZanBut)];
        [cell.imageViewShou addGestureRecognizer:tapShou];

        cell.butZan.tag = -1;
        [cell.butZan addTarget:self action:@selector(clickZanBut) forControlEvents:UIControlEventTouchUpInside];
    }else{
        cell.contentView.backgroundColor =  RGBColor(243, 243, 243);
        LSZDynamicCommentDetailsMg * mg = nil;
        mg = weakSelf.arrayTwoData[indexPath.row];
        cell.dynamicCommentDetailsMg = mg;
        cell.butZan.tag = indexPath.row+1;
        [cell.butZan addTarget:self action:@selector(clickZanButTwoSection:) forControlEvents:UIControlEventTouchUpInside];
        [cell.imageViewHeader tapGesture:^(UIGestureRecognizer *ges) {
            //个人信息页
            LSZPersonalInformationPageVC * vc = [[LSZPersonalInformationPageVC alloc]init];
            vc.uid =mg.uid;
            vc.imageViewHeader = mg.avatar;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }];
        UITapGestureRecognizer *tapNumber = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCommentDetailsNumber:)];
        [cell.labelZanNumber addGestureRecognizer:tapNumber];
        UIView *singleTapView = [tapNumber view];
        singleTapView.tag = indexPath.row+1;

        UITapGestureRecognizer *tapShou = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCommentDetailsShou:)];
        [cell.imageViewShou addGestureRecognizer:tapShou];
        UIView *tapShouTapView = [tapShou view];
        tapShouTapView.tag = indexPath.row+1;

        UILongPressGestureRecognizer *longPressGR = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(clickTwoMoveReport:)];
        //设定最小的长按时间 按不够这个时间不响应手势
        longPressGR.minimumPressDuration = 0.7;
        [cell addGestureRecognizer:longPressGR];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tapCommentDetailsNumber :(UITapGestureRecognizer *)tap
{
    UITapGestureRecognizer *singleTap = (UITapGestureRecognizer *)tap;
    [self initWithVideoZanDeatil:[singleTap view].tag];
}
-(void)tapCommentDetailsShou :(UITapGestureRecognizer *)tap
{
    UITapGestureRecognizer *singleTap = (UITapGestureRecognizer *)tap;
    [self initWithVideoZanDeatil:[singleTap view].tag];
}
-(void)setTableView
{
    self.tableViewCommentDetails = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-48) style:UITableViewStyleGrouped];
    self.tableViewCommentDetails.dataSource = self;
    self.tableViewCommentDetails.delegate = self;
    self.tableViewCommentDetails.estimatedRowHeight =0;
    self.tableViewCommentDetails.estimatedSectionFooterHeight =0;
    self.tableViewCommentDetails.estimatedSectionHeaderHeight =0;
    [self.tableViewCommentDetails setSeparatorInset:UIEdgeInsetsMake(0, 20, 0, 20)];
    [self.view addSubview:self.tableViewCommentDetails];
    [self.tableViewCommentDetails registerClass:[LSZAppraiseTableViewCell class] forCellReuseIdentifier:@"LSZAppraiseTableViewCell"];
    [self.tableViewCommentDetails registerClass:[LSZHeaderLabelCell class] forHeaderFooterViewReuseIdentifier:@"LSZHeaderLabelCell"];
    __weak typeof(self) weakSelf = self;
    weakSelf.tableViewCommentDetails.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        weakSelf.page = 1;
        //诗歌歌谱的分类
        [weakSelf GetAreplyListOfComments:weakSelf.page];
        [weakSelf.tableViewCommentDetails.mj_header endRefreshing];
    }];
    weakSelf.tableViewCommentDetails.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        weakSelf.page++;
        //诗歌歌谱的分类
        [weakSelf GetAreplyListOfComments:weakSelf.page];
        [weakSelf.tableViewCommentDetails.mj_footer endRefreshing];
    }];
    [LSZSpecialPackaging initWithAppraise:weakSelf.view share:1 :^(UIView * lowView,UITextView * textView,UILabel * label, UIButton * but, UIImageView * imageViewSend) {
        textView.delegate = weakSelf;
        weakSelf.lowView = lowView;
        weakSelf.textView = textView;
        label.text = @"点击此处说两句...";
        weakSelf.uilabel = label;
        imageViewSend.image = [UIImage imageNamed:@""];
        [imageViewSend tapGesture:^(UIGestureRecognizer *ges) {
            [self rightTwoDynamicCommentDetails];

        }];
        [but setTitleColor:titleColorLSZ forState:UIControlStateNormal];
        [but setTitle:@"发送" forState:UIControlStateNormal];
        [but tapGesture:^(UIGestureRecognizer *ges) {
            [self rightTwoDynamicCommentDetails];
        }];
    }];
    //监听键盘
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShowDetails:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHideDetails:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

    [self.view tapGesture:^(UIGestureRecognizer *ges) {
        [self clickSingleTap];
    }];
    self.tableViewCommentDetails.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self GetAreplyListOfComments :self.page];
            [self.tableViewCommentDetails.mj_header endRefreshing];
        });
    }];
    self.tableViewCommentDetails.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self GetAreplyListOfComments:self.page];
            [self.tableViewCommentDetails.mj_footer endRefreshing];
        });
    }];
    UIButton *leftbutton=[[UIButton alloc]initWithFrame:CGRectMake(30, 0, 60, 38)];
    [leftbutton setImage:[UIImage imageNamed:@"动态_白点"] forState:UIControlStateNormal];
    [leftbutton addTarget:self action:@selector(clickTwoMoveReport) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightitem=[[UIBarButtonItem alloc]initWithCustomView:leftbutton];
    self.navigationItem.rightBarButtonItem=rightitem;
}
-(void)rightTwoDynamicCommentDetails
{
    [self initWithUserCommentsOnResourcesResponseEvaluation:self.textView.text];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}
-(void)clickSingleTap
{
    [self.view endEditing:YES];
}
//当键盘出现或改变时调用
- (void)keyboardWillShowDetails:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    self.tableViewCommentDetails.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-self.lowView.frame.size.height-height);
    self.lowView.frame = CGRectMake(0, ScreenHeight-self.lowView.frame.size.height-height, ScreenWidth, self.lowView.frame.size.height);
    [UIView commitAnimations];
}
//当键退出时调用
- (void)keyboardWillHideDetails:(NSNotification *)aNotification{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    self.tableViewCommentDetails.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight- self.lowView.frame.size.height);
    self.lowView.frame = CGRectMake(0, ScreenHeight-self.lowView.frame.size.height, ScreenWidth, self.lowView.frame.size.height);
    [UIView commitAnimations];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSString * strLong = [textView.text stringByReplacingCharactersInRange:range withString:text];
    if (strLong.length == 0) {
        self.uilabel.hidden = NO;
    }else{
        if (strLong.length > 0 && self.uilabel.hidden == NO) {
            self.uilabel.hidden = YES;
        }
    }
    if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车，即按下return
        //在这里做你响应return键的代码
        [self initWithUserCommentsOnResourcesResponseEvaluation:strLong];
        [self clickSingleTap];
        return NO; //这里返回NO，就代表return键值失效，即页面上按下return，不会出现换行，如果为yes，则输入页面会换行
    }
    return YES;
}
#pragma mark - 用户对评论进行回复
-(void)initWithUserCommentsOnResourcesResponseEvaluation :(NSString *)str
{
    __weak typeof(self) weakSelf = self;
    if([[_UserM usercode] isEqualToString:@""]){
        [weakSelf gotoLogin];
        return;
    }
    if ((NullStringjudgment(NSStr(str))).length  == 0) {
        [self initWithtring:@"请输入您要评价的内容!"];
        return;
    }
    [LSZRequestData usersCommentOnResources:self.dynamicCommentDetailsMg.tid :self.dynamicCommentDetailsMg.id_id content:str :^(BOOL isOk, NSString * string, NSDictionary * dic) {
        if (isOk == YES) {
            weakSelf.uilabel.hidden = NO;
            weakSelf.textView.text = @"";
            [weakSelf GetAreplyListOfComments:weakSelf.page];
            [weakSelf setStringWarning:@"评价成功!"];
        }else{
            [weakSelf setStringWarning:str];
        }
    }];
}
#pragma mark - 对第一行的进行点赞
-(void)clickZanBut
{
    __weak typeof(self) weakSelf = self;
    if([[_UserM usercode] isEqualToString:@""]){
        [weakSelf gotoLogin];
        return;
    }
    [self clickDynamicZanManager:self.dynamicCommentDetailsMg row:0 :0];
}
#pragma mark - 对评论点赞
-(void)clickDynamicZanManager :(LSZDynamicCommentDetailsMg*)mg row:(NSInteger)row :(NSInteger)section
{
    NSString * ck = [[NSString alloc]init];
    NSString * mode = [[NSString alloc]init];
    if ([mg.is_admire isEqualToString:@"0"]) {
        ck = @"0";//点赞
        mode = @"";
    }else{
        ck = @"";//点赞
        mode = @"1";//取消点赞
    }
    [LSZRequestData theDynamicPointOfPraise:mg.id_id type:@"2" ck:ck mode:mode :^(BOOL isOk, NSString * string, NSDictionary * dic) {
        if (isOk == YES) {
            if([ck isEqualToString:@"0"]){
                mg.is_admire = @"1";

                mg.admire_num = [NSString stringWithFormat:@"%ld",(long)([mg.admire_num integerValue]+1)];
                [self initWithtring:@"点赞成功!"];
            }else{
                mg.is_admire = @"0";
                if ([mg.admire_num integerValue] == 0) {
                    mg.admire_num = 0;
                }else{
                    mg.admire_num = [NSString stringWithFormat:@"%ld",(long)([mg.admire_num integerValue]-1)];
                }
                [self initWithtring:@"取消点赞!"];
            }
            LSZAppraiseTableViewCell * cell = (LSZAppraiseTableViewCell *)[self.tableViewCommentDetails cellForRowAtIndexPath:[NSIndexPath indexPathForRow:row  inSection:section]];
            if([mode isEqualToString:@"1"]){
                cell.imageViewShou.image = [UIImage imageNamed:@"点赞"];
            }else{
                cell.imageViewShou.image = [UIImage imageNamed:@"我的_签到_留言_已点赞"];
            }
            cell.labelZanNumber.text = mg.admire_num;
        }else{
            [self initWithtring:string];
        }
    }];
}
#pragma mark - 回复的点赞
-(void)clickZanButTwoSection:(UIButton *)but
{
    [self initWithVideoZanDeatil:but.tag];
}
-(void)initWithVideoZanDeatil :(NSInteger)row
{
    __weak typeof(self) weakSelf = self;
    if([[_UserM usercode] isEqualToString:@""]){
        [weakSelf gotoLogin];
        return;
    }
    LSZDynamicCommentDetailsMg * mg = nil;
    mg = weakSelf.arrayTwoData[row-1];
    [self clickDynamicZanManager:mg row:row-1 :1];
}
#pragma mark - 对主评论进行举报按钮的单击事件
-(void)clickTwoMoveReport
{
    [self clickSecondaryMoveReportWithWhat:@"0"];
}
-(void)clickTwoMoveReport:(UILongPressGestureRecognizer *)lpGR
{
    if (lpGR.state == UIGestureRecognizerStateBegan) {//手势开始
        CGPoint point = [lpGR locationInView:self.tableViewCommentDetails];
        NSIndexPath *indexPath =  [self.tableViewCommentDetails indexPathForRowAtPoint:point];
        if (indexPath != nil){
            self.indexNum = indexPath.row;
        }
    }
    if (lpGR.state == UIGestureRecognizerStateEnded){
        //手势结束
        [self longPressDelete];//添加弹窗
    }
}
#pragma mark - 对评论举报点击事件
-(void)longPressDelete
{
    [self clickSecondaryMoveReportWithWhat:@"1"];
}
-(void)clickSecondaryMoveReportWithWhat:(NSString *)strWhat
{
    ACActionSheet *actionSheet = [[ACActionSheet alloc] initWithTitle:nil cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@[@"举报"] actionSheetBlock:^(NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            if ([[_UserM usercode] isEqualToString:@""]) {
                pushAccLoginVC;
                return;
            }else{
                if ([strWhat isEqualToString:@"0"]) {
                    [self jumpOfSecondaryReportInformation:self.dynamicCommentDetailsMg.username titleString:self.dynamicCommentDetailsMg.content tid:self.tid comment_id:self.dynamicCommentDetailsMg.id_id];
                }else{
                    LSZDynamicCommentDetailsMg * manager = nil;
                    manager = self.arrayTwoData[self.indexNum];
                    [self jumpOfSecondaryReportInformation:manager.username titleString:manager.content tid:self.tid comment_id:manager.id_id];
                }
            }
        }
    }];
    [actionSheet show];
}
-(void)jumpOfSecondaryReportInformation:(NSString *)name titleString:(NSString *)titleString tid:(NSString *)tid comment_id:(NSString *)comment_id
{
    LSZReportViewController * VC = [[LSZReportViewController alloc]init];
    VC.name = name;
    VC.titleString = titleString;
    VC.tid = tid;
    VC.type = @"1";
    VC.comment_id = comment_id;
    [self.navigationController pushViewController:VC animated:YES];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
